package com.junyidao.game.service;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.junyidao.game.Exception.BusinessException;
import com.junyidao.game.constant.BaseConstant;
import com.junyidao.game.constant.SysPrivConstant;
import com.junyidao.game.constant.SysUserConstant;
import com.junyidao.game.core.LoginInfo;
import com.junyidao.game.mapper.SysUserMapper;
import com.junyidao.game.mapper.SysUserPrivRelaMapper;
import com.junyidao.game.mapper.SysUserRoleRelaMapper;
import com.junyidao.game.mapper.TChannelUserRelaMapper;
import com.junyidao.game.pojo.*;
import com.junyidao.game.util.Md5Util;
import com.junyidao.game.vo.SysPrivVo;
import com.junyidao.game.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Created by HP on 2016/8/10.
 */
@Service
@Transactional
public class UserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SequenceService sequenceService;

    @Autowired
    private TChannelUserRelaMapper channelUserRelaMapper;

    @Autowired
    private SysUserPrivRelaMapper sysUserPrivRelaMapper;

    @Autowired
    private SysUserRoleRelaMapper sysUserRoleRelaMapper;

    @Autowired
    private SysPrivService sysPrivService;

    public Map<String, Object> getAll(SysUser sysUser) {
        PageHelper.startPage(sysUser.getPage(), sysUser.getRows());
        sysUser.setPuid(LoginInfo.getUser().getUid());
        List<SysUser> list = sysUserMapper.selectAllBySysUser(sysUser);
        PageInfo page = new PageInfo(list);
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("count", page.getTotal());
        return map;
    }

    public void activate(String uids, String statusCode) {
        List<Integer> ids = JSONArray.parseArray(uids, Integer.class);
        Map<String, Object> map = new HashMap<>();
        map.put("uids", ids);
        map.put("statusCode", statusCode);
        sysUserMapper.activateSysUser(map);
    }

    public void addSysUser(SysUser sysUser, String channelIds, String privIds) {
        SysUser user = new SysUser();
        user.setAccountName(sysUser.getAccountName());
        List<SysUser> userList = sysUserMapper.select(user);
        if (userList.size() > 0) {
            BusinessException.throwException(1, "账号已存在，请修改账号名");
        }
        SysUser loginUser = LoginInfo.getUser();
        Integer id = sequenceService.getNextSequence("USER_ID");
        sysUser.setUid(id);
        sysUser.setPassword(Md5Util.digestMD5(sysUser.getPassword()));
        sysUser.setCreateTime(new Date());
        sysUser.setEffectFlag(SysUserConstant.EFFECT);
        sysUser.setDeleteFlag(SysUserConstant.NORMAL);
        sysUser.setStatusCode(SysUserConstant.NORMAL);
        if (loginUser != null) {
            if (loginUser.getLevelCode().equals(SysUserConstant.LEVEL_ONE)) {
                sysUser.setLevelCode(SysUserConstant.LEVEL_TWO);
            } else if (loginUser.getLevelCode().equals(SysUserConstant.LEVEL_TWO)) {
                sysUser.setLevelCode(SysUserConstant.LEVEL_THREE);
            } else if (loginUser.getLevelCode().equals(SysUserConstant.LEVEL_THREE)) {
                BusinessException.throwException(1, "您无权创建账号");
            }
            sysUser.setPuid(loginUser == null ? null : loginUser.getUid());
        } else {
            sysUser.setPuid(0);
        }

        sysUserMapper.insert(sysUser);

        if (!StringUtils.isEmpty(channelIds)) {
            List<Integer> idList = JSONArray.parseArray(channelIds, Integer.class);
            insertChannelUserRela(idList, sysUser.getUid());
        }
        if (!StringUtils.isEmpty(privIds)) {
            List<Integer> privIdList = JSONArray.parseArray(privIds, Integer.class);
            insertPrivUserRela(privIdList, sysUser.getUid());
        }
    }

    // TODO: 2016/10/7   注册账号，上级账号是多少
    public void addSysUser(SysUser sysUser) {
        SysUser user = new SysUser();
        user.setAccountName(sysUser.getAccountName());
        List<SysUser> userList = sysUserMapper.select(user);
        if (userList.size() > 0) {
            BusinessException.throwException(1, "账号已存在，请修改账号名");
        }
        SysUser loginUser = LoginInfo.getUser();
        Integer id = sequenceService.getNextSequence("USER_ID");
        sysUser.setUid(id);
        sysUser.setPassword(Md5Util.digestMD5(sysUser.getPassword()));
        sysUser.setCreateTime(new Date());
        sysUser.setEffectFlag(SysUserConstant.DIS_EFFECT);
        sysUser.setDeleteFlag(SysUserConstant.NORMAL);
        sysUser.setStatusCode(SysUserConstant.NORMAL);
        sysUser.setPuid(0);

        sysUserMapper.insert(sysUser);
    }

    public void updateSysUser(SysUser sysUser, String channelIds, String privIds) {
        SysUser user = new SysUser();
        user.setDeleteFlag(SysUserConstant.NORMAL);
        user.setAccountName(sysUser.getAccountName());
        List<SysUser> userList = sysUserMapper.select(user);
        if (userList.size() > 1) {
            BusinessException.throwException(1, "账号名已存在，请修改账号名");
        } else if (userList.size() == 1) {
            if (!userList.get(0).getUid().equals(sysUser.getUid())) {
                BusinessException.throwException(1, "账号名已存在，请修改账号名");
            }
        }
//        sysUser.setPassword(Md5Util.digestMD5(sysUser.getPassword()));
        sysUserMapper.updatePartByPrimaryKey(sysUser);


        TChannelUserRela rela1 = new TChannelUserRela();
        rela1.setUid(sysUser.getUid());
        channelUserRelaMapper.delete(rela1);

        List<Integer> idList = JSONArray.parseArray(channelIds, Integer.class);
        insertChannelUserRela(idList, sysUser.getUid());

        SysUserPrivRela rela = new SysUserPrivRela();
        rela.setUid(sysUser.getUid());
        sysUserPrivRelaMapper.delete(rela);

        List<Integer> privIdList = JSONArray.parseArray(privIds, Integer.class);
        insertPrivUserRela(privIdList, sysUser.getUid());
    }

    public void insertChannelUserRela(List<Integer> idList, Integer uid) {
        if (idList.size() > 0) {
            for (Integer id : idList) {
                Integer cid = sequenceService.getNextSequence("CHANNEL_USER_ID");
                TChannelUserRela rela = new TChannelUserRela();
                rela.setChannelUserId(cid);
                rela.setChannelId(id);
                rela.setUid(uid);
                rela.setStatusCode("0");
                channelUserRelaMapper.insert(rela);
            }
        }
    }

    public void insertPrivUserRela(List<Integer> idList, Integer uid) {
        if (idList.size() > 0) {
            for (Integer id : idList) {
                Integer rid = sequenceService.getNextSequence("USER_PRIV_RELA_ID");
                SysUserPrivRela rela = new SysUserPrivRela();
                rela.setUserPrivRelaId(rid);
                rela.setUid(uid);
                rela.setGrantFlag(BaseConstant.STATUS_NORMAL);
                rela.setPrivId(id);
                sysUserPrivRelaMapper.insert(rela);
            }
        }
    }

    public String checkLogin(String accountName, String password) {
        if (StringUtils.isEmpty(accountName) || StringUtils.isEmpty(password)) {
            BusinessException.throwException(1, "用户名或密码不能为空");
        }
        SysUser par = new SysUser();
        par.setAccountName(accountName);
        par.setPassword(password);
        List<SysUser> userList = sysUserMapper.select(par);
        if (userList.size() == 0) {
            BusinessException.throwException(1, "用户名或密码错误");
        }
        SysUser user = userList.get(0);
        String firstUrl = "";
        if (!user.getEffectFlag().equals(SysUserConstant.EFFECT)) {
            firstUrl = "/login/checkRegister";
            LoginInfo.setUser(user);
            return firstUrl;
        }
        SysUser supPar = new SysUser();
        supPar.setUid(user.getPuid());
        SysUser supUser = sysUserMapper.selectOne(supPar);
        if (supUser != null) {
            if (supUser.getStatusCode().equals(BaseConstant.STATUS_DELETE)) {
                BusinessException.throwException(1, "上级账号已被注销，您无权再登陆了");
            } else {
                SysUser supPar2 = new SysUser();
                supPar2.setUid(supUser.getPuid());
                SysUser supUser2 = sysUserMapper.selectOne(supPar2);
                if (supUser2 != null) {
                    if (supUser2.getStatusCode().equals(BaseConstant.STATUS_DELETE)) {
                        BusinessException.throwException(1, "上级账号已被注销，您无权再登陆了");
                    }
                }
            }
        }
        // 获取用户权限 根据角色
        List<SysPrivVo> privList = sysPrivService.getUserRolePrivList(user.getUid());
        if (privList.size() == 0) {
            // 如果根据角色 没有权限，则根据uid获取
            privList = sysPrivService.getUserPrivList(user.getUid());
        }
        //获取菜单
        List<SysPrivVo> menuList = getMenuList(privList);
        //设置SESSION
        LoginInfo.setSysPriv(privList);
        LoginInfo.setMenu(menuList);
        LoginInfo.setUser(user);


        if (menuList.size() > 0) {
            if (menuList.get(0).getSubPriv().size() > 0) {
                firstUrl = menuList.get(0).getSubPriv().get(0).getPrivResAddr();
            }
        }
        return firstUrl;
    }

    /**
     * 获取以及菜单及其子菜单
     *
     * @param privList
     * @return
     */
    public List<SysPrivVo> getMenuList(List<SysPrivVo> privList) {
        List<SysPrivVo> levelOne = new ArrayList<>();
        Map<Integer, List<SysPrivVo>> allMap = new HashMap<>();
        for (SysPrivVo priv : privList) {
            List<SysPrivVo> cList = allMap.get(priv.getPprivId());
            if (cList == null) {
                cList = new ArrayList<>();
                allMap.put(priv.getPprivId(), cList);
            }
            cList.add(priv);
            if (priv.getPprivId() == 0 && priv.getPrivType().equals(SysPrivConstant.SYS_PRIV_MENU)) {
                levelOne.add(priv);
            }
        }
        for (SysPrivVo vo : levelOne) {
            vo.setSubPriv(allMap.get(vo.getPrivId()));
        }
        return levelOne;
    }

    public SysUser selectByPrimaryKey(Integer uid) {
        SysUser user = new SysUser();
        user.setUid(uid);
        List<SysUser> users = sysUserMapper.select(user);
        return users.size() > 0 ? users.get(0) : null;
    }

    public Map<String, Object> selectAllByGroup(UserVo user) {
        PageHelper.startPage(user.getPage(), user.getRows());
        user.setUid(LoginInfo.getUser().getUid());
        List<SysUser> list = sysUserMapper.selectAllByGroup(user);
        PageInfo page = new PageInfo(list);
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("count", page.getTotal());
        return map;
    }

    public Map<String, Object> getUserByChannel(UserVo userVo) {
        PageHelper.startPage(userVo.getPage(), userVo.getRows());
        userVo.setPuid(LoginInfo.getUser().getUid());
        List<SysUser> list = sysUserMapper.selectAllByChannel(userVo);
        PageInfo page = new PageInfo(list);
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("count", page.getTotal());
        return map;
    }

    public void addSysUser(SysUser sysUser, String roleIds) {
        SysUser user = new SysUser();
        user.setAccountName(sysUser.getAccountName());
        List<SysUser> userList = sysUserMapper.select(user);
        if (userList.size() > 0) {
            BusinessException.throwException(1, "账号已存在，请修改账号名");
        }
        SysUser loginUser = LoginInfo.getUser();
        Integer id = sequenceService.getNextSequence("USER_ID");
        sysUser.setUid(id);
        sysUser.setPassword(Md5Util.digestMD5(sysUser.getPassword()));
        sysUser.setCreateTime(new Date());
        sysUser.setEffectFlag(SysUserConstant.EFFECT);
        sysUser.setDeleteFlag(SysUserConstant.NORMAL);
        sysUser.setStatusCode(SysUserConstant.NORMAL);
        sysUser.setLevelCode(SysUserConstant.LEVEL_ONE);
        if (loginUser != null) {
            sysUser.setPuid(loginUser == null ? null : loginUser.getUid());
        } else {
            sysUser.setPuid(0);
        }

        sysUserMapper.insert(sysUser);

        if (!StringUtils.isEmpty(roleIds)) {
            List<Integer> idList = JSONArray.parseArray(roleIds, Integer.class);
            insertUserRoleRela(idList, sysUser.getUid());
        }

    }

    public void insertUserRoleRela(List<Integer> idList, Integer uid) {
        if (idList.size() > 0) {
            for (Integer id : idList) {
                Integer cid = sequenceService.getNextSequence("USER_ROLE_RELA_ID");
                SysUserRoleRela rela = new SysUserRoleRela();
                rela.setUserRoleRelaId(cid);
                rela.setRoleId(id);
                rela.setUid(uid);
                sysUserRoleRelaMapper.insert(rela);
            }
        }
    }

    public void updateSysUser(SysUser sysUser, String roleIds) {
        SysUser user = new SysUser();
        user.setDeleteFlag(SysUserConstant.NORMAL);
        user.setAccountName(sysUser.getAccountName());
        List<SysUser> userList = sysUserMapper.select(user);
        if (userList.size() > 1) {
            BusinessException.throwException(1, "账号名已存在，请修改账号名");
        } else if (userList.size() == 1) {
            if (!userList.get(0).getUid().equals(sysUser.getUid())) {
                BusinessException.throwException(1, "账号名已存在，请修改账号名");
            }
        }
        sysUserMapper.updatePartByPrimaryKey(sysUser);

        SysUserRoleRela rela = new SysUserRoleRela();
        rela.setUid(sysUser.getUid());
        sysUserRoleRelaMapper.delete(rela);

        List<Integer> idList = JSONArray.parseArray(roleIds, Integer.class);
        insertUserRoleRela(idList, sysUser.getUid());

    }

    public void updatePassword(String password, String passwordOld) {
        SysUser user = LoginInfo.getUser();
        if (!user.getPassword().toUpperCase().equals(passwordOld.toUpperCase())) {
            BusinessException.throwException(1, "原密码错误");
        }
        SysUser newUser = new SysUser();
        newUser.setUid(user.getUid());
        newUser.setPassword(password.toUpperCase());
        sysUserMapper.updatePartByPrimaryKey(newUser);
    }

    public void updateBind(String mobil, String email) {
        if (!StringUtils.isEmpty(mobil) || !StringUtils.isEmpty(email)) {
            SysUser user = new SysUser();
            user.setUid(LoginInfo.getUser().getUid());
            user.setMobil(mobil);
            user.setEmail(email);
            sysUserMapper.updatePartByPrimaryKey(user);
            if (!StringUtils.isEmpty(mobil)) {
                LoginInfo.getUser().setMobil(mobil);
            }
            if (!StringUtils.isEmpty(email)) {
                LoginInfo.getUser().setEmail(email);
            }
        }
    }

    public SysUser getUser(String accountName) {
        SysUser sysUser = new SysUser();
        sysUser.setAccountName(accountName);
        List<SysUser> list = sysUserMapper.select(sysUser);
        return list.size() > 0 ? list.get(0) : null;
    }

    public List<SysUser> getSubUser(SysUser user) {
        List<SysUser> list = sysUserMapper.getSubUser(user);
        return list;
    }
}
